import 'package:flutter/material.dart';

/// 点击非输入框时收起键盘
class HideKeyboardWidget extends StatefulWidget {
  final Widget child;

  const HideKeyboardWidget({super.key, required this.child});

  @override
  HideKeyboardWidgetState createState() => HideKeyboardWidgetState();
}

class HideKeyboardWidgetState extends State<HideKeyboardWidget> {
  FocusNode? _emptyFocusNode;

  @override
  void initState() {
    super.initState();
    _emptyFocusNode = FocusNode();
  }

  @override
  void dispose() {
    _emptyFocusNode?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: hideKeyboard,
      child: widget.child,
    );
  }

  void hideKeyboard() {
    if (_emptyFocusNode != null) {
      FocusScope.of(context).requestFocus(_emptyFocusNode);
    }
  }

  static HideKeyboardWidgetState findBy(GlobalKey key) {
    return key.currentState as HideKeyboardWidgetState;
  }

  /// 主动隐藏键盘
  static void hideKeyboardByKey(GlobalKey key) {
    findBy(key).hideKeyboard();
  }
}
